package is.progetto1.aritmeticExpression.builder.impl;

import java.io.IOException;

import is.progetto1.aritmeticExpression.Expression;
import is.progetto1.aritmeticExpression.Utility;
import is.progetto1.aritmeticExpression.builder.DirectorIF;
import is.progetto1.aritmeticExpression.builder.ExpressionBuilderIF;
import is.progetto1.aritmeticExpression.builder.InputManagerIF;

public final class Director implements DirectorIF{
	
	private InputManagerIF im=null;
	private ExpressionBuilderIF eb=null;
	private String symble=null;
	
	public Director(InputManagerIF im, ExpressionBuilderIF eb) {
		super();
		this.im = im;
		this.eb = eb;
	}
	
	@Override
	public Expression costruct() throws IOException{
		symble = im.nextSymble();
		int nbrake=0;
		while (!symble.equals(InputManagerIF.EOS)) {
			if (symble.equals("(")) {
				eb.buildOperator();
				nbrake++;
			} else if (symble.matches(Utility.REGEX_NUMBER)||symble.matches(Utility.REGEX_VARIABLE)) {
				if(nbrake==0){
					throw new IOException();
				}
				eb.buildOperand(symble);
			} else if(symble.equals("+")||symble.equals("-")||symble.equals("*")||symble.equals("/")){
				eb.fixOperator(symble);
			}else if (symble.equals(")")){
				eb.endsOperator();
				nbrake--;
			} 
			else{
				throw new RuntimeException(symble + " inaspected");
			}
			symble = im.nextSymble();
		}//while
		return eb.getResult();
	}
}
